<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <button>下载</button>
  <progress value="0" max="100"></progress>
  <span>进度：</span>
  <span class="speed">0kb/s</span>
  <script>
    const xhr = new XMLHttpRequest()

    document.querySelector("button").onclick = function () {
      xhr.open("get", "/download", true)
      let sTime;
      let sSize;
      xhr.onloadstart = function () {
        console.log("开始下载");
        sTime = Date.now()
        sSize = 0
      }
      xhr.onprogress = function (event) {
        // event.total
        // event.loaded
        // 下载进度
        const progress = (event.loaded / event.total) * 100
        document.querySelector("progress").value = progress
        document.querySelector("span").innerHTML = `进度：${progress.toFixed(2)}%`

        // 下载速度
        let cTime = Date.now()
        let dTime = cTime - sTime // 毫秒
        let dSize = event.loaded - sSize
        console.log(dSize, dTime)
        let speed = (dSize / dTime) * 1000
        console.log(speed)


        if (speed > 1024 * 1024) {
          speed = (speed / (1024 * 1024)).toFixed(2) + "mb/s"
        } else if (speed > 1024) {
          speed = (speed / 1024).toFixed(2) + "kb/s"
        } else {
          speed = speed.toFixed(2) + "b/s"
        }

        document.querySelector(".speed").innerHTML = speed

        sSize = event.loaded
        sTime = cTime

      }
      // 设置响应数据的数据类型  word/excel/ppt -> blob
      xhr.responseType = "blob"
      xhr.onload = function () {
        console.log("请求成功");
        // console.log(xhr.response);

        // // 下载文件
        // let URL = window.URL || window.webkitURL
        // let objectUrl = URL.createObjectURL(xhr.response);
        // let a = document.createElement('a');
        // a.href = objectUrl;
        // a.download = "ceshi.ppt";
        // document.body.appendChild(a);
        // a.click();
        // a.remove();
      }


      xhr.onloadend = function () {
        console.log("请求完成");
      }

      xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded')
      xhr.send()
    }
  </script>
</body>

</html>
